<template>
  <div class="flex flex-col" style="height: 100%;position: relative;padding-bottom: 40px;">

    <!--抬头tabs -->
    <div class="card-container">
      <span v-for="(item) in dictList" :key="item.dictValue" @click="tabChange(item.dictValue)" 
        :class="{'x-tab-item':true, 'active':activeKey==item.dictValue}">
        {{ item.dictLabel}}
      </span>
      <span :class="{'x-tab-item':true, 'active':activeKey=='mb'}" @click="tabChange('mb')">预设指标组合</span>
   </div>
    <div class="flex pl-2 pt-2" v-if="activeKey=='mb'" style="border:1px solid #e5e5e5;background-color: #f9f9f9;">
      <a-list :grid="{ gutter: 12, column: 2 }" :data-source="mblist" class="w-full" >
        <template #renderItem="{ item }">
          <a-list-item key="item.title" size="small"  class="text-black" @click="toggleTmp(item)">
            <div :class="{'flex':true, 'flex-col':true, 'mb-2':true, 'ml-2':true, 'mb-item':true, 'active':activeMb==item.id}">
              <div class="flex justify-between items-center mr-2" >
                <span class="cursor-pointer" v-if="item.issys=='0'">{{item.tmpname}} </span>
                <span class="cursor-pointer" v-else style="font-weight: bold;">{{item.tmpname}} </span>
                <Popconfirm
                  title="确认要删除该模板吗?"
                  ok-text="删除"
                  cancel-text="取消"
                  placement="left"
                  @confirm="deletemb(item)"
                  @cancel="cancel">

                <div class="font-blod cursor-pointer text-gray-500" v-if="item.issys=='0'">
                  <a-tooltip>
                    <template #title>删除{{item.tmpname}}</template>
                     <DeleteOutlined title="点击删除"/>
                  </a-tooltip>
                </div>

              </Popconfirm>
              </div>
              <!-- <span :class="{'cursor-pointer':true, 'text-gray-300':item.id!=activeMb}" >{{item.createDate}} </span> -->
            </div>
          </a-list-item>
          
        </template>
      </a-list>
    </div>

    <div class="flex pl-2 pt-2" v-else 
      style="border:1px solid #e5e5e5;background-color: #f9f9f9;border-radius: 5px;padding:1em;max-height: 35%;overflow-y: scroll;">
      <a-list :grid="{ gutter: 0, column: 3 }" :data-source="zhibiaolist" class="w-full" >
        <template #renderItem="{ item }">
          <a-list-item key="item.title" size="small"  
            class="cursor-pointer text-black" @click="addGroupItem(item)" style="height:14px;">
            <div style="font-family: Roboto;color: #000;">
              <PlusCircleFilled title="点击添加指标筛选条件" /><span class="ml-2">{{item.zbname}}</span>
              </div>
          </a-list-item>
          
        </template>
      </a-list>
    </div>
    <div class="text-lg font-bold mb-2" style="margin-top:.5em;">条件面板&nbsp;&nbsp;<span style="font-size: 14px;font-weight: 500;">请选择条件</span></div>
    <div class="flex flex-col" style="overflow-y: scroll;padding:0 1em; padding-bottom: 40px; 
      padding-top:12px;border:1px solid #e5e5e5">
      <!-- group-->
      <div class="flex flex-col"  v-for="(item, index) in currentTabTiaoJianList" :key="index">
          <!-- 头&&行-->
          <div class="flex flex-col unselected-item p-3" :class="{ 'selected-item':index==selectedItem}" @click="selectGroup(index)">
              <!-- 头部-->
              <div class="flex justify-between mt-1">
                      <div class="flex flex-1 mr-1">指标</div>
                      <div class="flex flex-1 mr-1">条件</div>
                      <div class="flex flex-1 mr-1">对比指标</div>
                      <div class="flex mr-1" style="flex: 0.5">倍率</div>
                      <div class="flex mr-1" >
                        <div class="text-gray-600" style="margin-left: auto; cursor: pointer;" title="删除该条件组" @click="deleteGroup(index)"><DeleteOutlined v-show="index!=0"/></div>
                      </div>
              </div>
              <!-- 行循环 -->
              <div class="flex justify-between w-full items-center mt-1" style="margin-top:1em" :key="childitem.zbkey"
                 v-for="(childitem, childindex) in item.tiaojianchildlist" >
                    
                    <div class="flex flex-1 mr-1">
                      <a-input :value="childitem.zbname" style="width:100%;border-radius: 5px;"></a-input>
                    </div>
                    <div class="flex flex-1 mr-1" v-if="'BOOL'!=childitem.valuetype">
                      <a-select
                      style="width:100%;"
                        label-in-value
                        :options="bjoptions"
                        :value="childitem.zbcomparefuhao"
                        @change="fuhaochange($event, index,childindex)">
                      </a-select>
                    </div>
                    <div class="flex flex-1 mr-1"  v-if="'BOOL'!=childitem.valuetype">
                       <a-select
                        style="width:100%;border-radius: 5px;;"
                            v-if="childitem.zbcomparetype=='0'"
                          label-in-value
                          :options="childitem.zbcompareList"
                          :value="childitem.zbcomparevalue"
                          @change="compareValuechange($event, index,childindex)">
                        </a-select>

                      <a-input :placeholder="childitem.zbcompareinputalt" v-else v-model:value="childitem.zbcomparevalue">
                        <template #suffix>
                            <UnorderedListOutlined alt="选择模式" @click="changeToSelectMode(index,childindex)" v-if="childitem.cancompareList=='1'"></UnorderedListOutlined>
                         </template>
                      </a-input>
                    </div>

                    <div class="flex mr-1" style="flex:0.5" v-if="'BOOL'!=childitem.valuetype">
                      <a-input v-model:value="childitem.zbbeilv" style="border-radius: 5px;"></a-input>
                    </div>
                    <div class="flex items-center justify-center"  @click="deleteGroupItem(index,childindex)">
                      <span class="text-red-500"><MinusCircleFilled title="删除该条件" style="cursor: pointer;"/></span>
                    </div>
              </div>
          </div>
          <!-- 如果是最后一列，显示增加或条件组-->
          <div class="flex justify-center" style="flex-direction: column;align-items: center;justify-content: center;">
              <PlusCircleOutlined v-if="index<(currentTabTiaoJianList.length-1)" class="add-group" @click="addGroup(index)" title="添加OR条件组" style="color: #ccc;cursor: pointer;font-size: 18px;"/>
              <PlusCircleOutlined v-if="index==(currentTabTiaoJianList.length-1)" class="add-group-last" @click="addGroup(index)" title="添加OR条件组" style="color: #ccc;cursor: pointer;font-size: 18px;"/>
          </div>
        </div>
      </div>
      
      <!-- 底部按钮组 -->
      <div class="flex" style="width:100%;position: absolute;bottom:-12px;opacity: .9;">

          <a-button class="flex" type="default" rounded @click="clearAll" v-if="activeKey!='mb'">
            重置
          </a-button>
          <div class="flex ml-2" style="line-height: 30px;">共<span style="color: #025FFF;font-weight: bold;font-size: 16px;display: inline-block;padding:0 .2em">{{ seachTotalCount }}</span>支股票符合条件</div>
          <div class="flex"  style="margin-left: auto;">
            <a-button type="default" rounded @click="{activeMb=null,mbnamevalue=null; tianxieMbName();}" v-if="activeKey!='mb'">
            存为选股模版
           </a-button>
           <a-button type="default" rounded @click="tianxieMbName" v-if="activeKey=='mb' 
              && mblist.length>0 
              &&activeMb
              && (getCurrentUserId()=='system' || mblist.find(item=>item.id==activeMb).issys=='0')
               ">
            保存
           </a-button>
           <div class="flex" style="margin-left: auto;margin-left: .5em;"> 
              <a-button type="primary" rounded @click="beginSearchStock" :loading="beginSeaerchStockLoading">
              开始选股
              </a-button>
           </div>

          </div>
      </div>

      <!-- 保存-->
      <a-modal v-model:visible="visibleSave" title="保存模版" :width="360">
        <div class="flex m-6 flex-col">
           <span class="mb-3" style="text-align: left;">请输入模版名称:</span>
           <a-input v-model:value="mbnamevalue" placeholder="请输入模版名称" />
        </div>
        <template v-slot:footer>
          <div class="flex" style="padding-bottom: .5em;align-items: end;justify-content: end;">
            <a-button class="flex" type="default" @click="{visibleSave = false;}">取消</a-button>
            <a-button class="flex" type="primary" @click="handlesaveOk">确定</a-button>
          </div>
      </template>
      </a-modal>
    </div>
</template>
<script lang="ts">
import { Popconfirm, message } from 'ant-design-vue';
import { ref,onMounted,computed } from 'vue';
import { getZbListForSelectStock } from '/@/api/dp/column/dpColumn';
import { dpTmpjsonFrontSave,frontlist,frontdelusermb } from '/@/api/dp/stocktmp/dpTmpjson';
import { SettingOutlined,PlusCircleOutlined,MinusCircleOutlined,DeleteOutlined,PlusOutlined,ProfileOutlined,UnorderedListOutlined, MinusCircleFilled, PlusCircleFilled} from '@ant-design/icons-vue';
import {Tabs,Select, Input, Button, List, ListItem,Modal } from 'ant-design-vue';
import { getCurrentUserId } from '/@/utils/currentUser';

export default {
  components: {
    AModal:Modal,
    ATabs:Tabs,
    ASelect:Select,
    AButton: Button,
    AInput: Input,
    AList: List,
    AListItem: ListItem
  },
};

</script>

<script lang="ts" setup>  
  const $emit = defineEmits(['addOrRemoveCols', 'filterStockOfZhibiao'])
  defineExpose({refreshFilterTotalData});
  const beginSeaerchStockLoading = ref(false);
  const mblist=ref([]);
  const dictList=ref([]);
  const zhibiaolist=ref([]);
  const zhibiaolistMap=ref();
  const activeMb = ref();
  const seachTotalCount = ref(0);
  const tiaojianlist = ref([
    {"tiaojianchildlist":[]}
  ]);
  const activeKey=ref('1');

  const bjoptions=ref([{
    value:'0',
    label:'大于'
  },{
    value:'1',
    label:'等于'
  },{
    value:'2',
    label:'小于'
  },{
    value:'3',
    label:'大于等于'
  },{
    value:'4',
    label:'小于等于'
  }]);

  const currentTabTiaoJianList = computed(()=> {
    return tiaojianlist.value;
  });

  function refreshFilterTotalData(data) {
    seachTotalCount.value = data;
  }

  onMounted(async() => {
    await getZhibiaoList();
    await getmblist();
  });

  function toggleTmp(item) {
    if(item.id!=activeMb.value){
      activeMb.value = item.id;
      mbnamevalue.value = item.tmpname;
      viewMb(mblist.value.find(data=>data.id==item.id));
      beginSearchStock();
    } else {
      activeMb.value = null;
      mbnamevalue.value = null;
    }
  }
  
  function beginSearchStock() {
    let validText = tiaojianValidate();
    if(validText){
      message.error(validText);
      return;
    }
    beginSeaerchStockLoading.value = true;
    $emit('filterStockOfZhibiao', JSON.stringify(tiaojianlist.value));
    setTimeout(()=> {
      beginSeaerchStockLoading.value = false;
    }, 800);
  }

  async function getZhibiaoList(){
    const res=await getZbListForSelectStock();
    dictList.value=res.dictList;
    zhibiaolistMap.value=res.typeZbList;
    zhibiaolist.value = zhibiaolistMap.value[activeKey.value];
  }

  async function getmblist(){
    const res=await frontlist();
    mblist.value=res;
  }

  /**
   * 切换tab
   * @param key 
   */
  function tabChange(key){
    selectedItem.value = 0;
    activeKey.value = key;
    if(key=='mb'){
      return;
    }

    zhibiaolist.value=zhibiaolistMap.value[key];
  }

  const selectedItem=ref(0);

  function selectGroup(item){
    selectedItem.value=item;
  }

  function addGroup(index) {
    let currentTiaojianList = tiaojianlist.value;
    currentTiaojianList.splice(index+1,0, {
      tiaojianchildlist:[]
    });
    selectGroup(currentTiaojianList.length-1)
  }

  function addGroupItem(item) {
    let currentTiaojianList = tiaojianlist.value;
    
    if(currentTiaojianList.length==1){
      selectedItem.value = 0;
    }
    currentTiaojianList[selectedItem.value].tiaojianchildlist.push(JSON.parse(JSON.stringify(item)));
  }

  function deleteGroup(index){
    let currentTiaojianList = tiaojianlist.value;
    currentTiaojianList.splice(index, 1);
  }

  function deleteGroupItem(index,child){
    let currentTiaojianList = tiaojianlist.value;
    currentTiaojianList[index].tiaojianchildlist.splice(child, 1);
  }



  function fuhaochange(e,index,childindex){
    
    tiaojianlist.value[index].tiaojianchildlist[childindex].zbcomparefuhao=e.value;
  }

  function compareValuechange(e,index,childindex){
    let currentTiaojianList = tiaojianlist.value;
    if(e.value=='-1'){
      //切换为输入模式
      currentTiaojianList[index].tiaojianchildlist[childindex].zbcomparetype="1";
      currentTiaojianList[index].tiaojianchildlist[childindex].zbcomparevalue='';
      currentTiaojianList[index].tiaojianchildlist[childindex].zbcompareinputalt=e.label;
    }else{
      currentTiaojianList[index].tiaojianchildlist[childindex].zbcomparevalue=e.value;
    }
  }
  //切换为下拉选择模式
  function changeToSelectMode(index,childindex){
    let currentTiaojianList = tiaojianlist.value;
    currentTiaojianList[index].tiaojianchildlist[childindex].zbcomparetype="0";
    currentTiaojianList[index].tiaojianchildlist[childindex].zbcomparevalue='';
  }

  //保存模版
  const mbnamevalue=ref('');
  const visibleSave=ref(false);

  function tiaojianValidate(){
    let tiaojian = tiaojianlist.value;
    for(var i=0; i<tiaojian.length; i++) {
      let item = tiaojian[i];
      let childItems = item['tiaojianchildlist'];
      for(var t=0; t<childItems.length; t++) {
        let childItem = childItems[t];
        if(childItem.valuetype!='BOOL') {
          if(!childItem.zbcomparefuhao ||!childItem.zbcomparevalue){
            return "选股条件不完整，请检查";
          }
        } else {
          if(!childItem.zbname) {
            return "选股条件不完整，请检查";
          }
        }
      }
    }
    return "";
  }

  function tianxieMbName() {
    let validText = tiaojianValidate();
    if(validText){
      message.error(validText);
      return;
    }
    visibleSave.value=true;
  }

  async function updateMb(){
    let id = activeMb.value;
    let tmp = mblist.value.find(item=>item.id==id);
    if(!tmp) {
      return;
    }
    var obj  = {
      id:id,
      tmpname:tmp.tmpname,
      tmptype: tmp.tmptype,
      tmpjson:JSON.stringify(tiaojianlist.value)
    }
    const res=await dpTmpjsonFrontSave(obj);
    if(res?.result=='true'){
      //提示成功
      getmblist();
      message.success('保存成功');
    }else{
      //提示失败
      message.error('保存失败');
    }
  }

  /**
   * 保存选股模板
   */
  async function handlesaveOk() {
    if(!mbnamevalue.value) {
      message.error('请输入模板名称')
      return;
    }
    let id = activeMb.value;
    var obj= {
      id:id,
      tmpname:mbnamevalue.value,
      tmptype: activeKey.value,
      tmpjson:JSON.stringify(tiaojianlist.value)
    };
    const res=await dpTmpjsonFrontSave(obj);
    if(res?.result=='true'){
      //提示成功
      visibleSave.value=false;
      getmblist();
      message.success('保存成功');
    }else{
      //提示失败
      message.error('保存失败');
    }
  }
  function clearAll(){
    tiaojianlist.value =  [
        {"tiaojianchildlist":[]}
    ]
  }

  function viewMb(mb) {
    if(!mb){
      clearAll();
    }else {
      tiaojianlist.value=JSON.parse(mb.tmpjson);
    }
  }

  async function deletemb(obj) {
      await frontdelusermb({id:obj.id});
      getmblist();
  }
</script>
<style  lang="less" scoped>
.card-container{
  margin-bottom: .5em;
}
.add-group::before,.add-group-last::before{
  height: 8px;
  width: 2px;
  background: #cccccc;
  content: '';
  display: flex;
  margin-left: 8px;
}

.add-group::after{
  height: 8px;
  width: 2px;
  background: #cccccc;
  content: '';
  display: flex;
  margin-left: 8px;
}
.selected-item {
  border: 2px solid #025FFF !important;  /*加边框的颜色可以自定义 */
  /* background:#f5f5f5; */
}

.unselected-item {
  border: 1px solid #cccccc; /* 加边框的颜色可以自定义 */
}
.mb-item {
  padding: .5em; 
  background-color: #ffffff; 
  border-radius:5px; 
  border: 1px solid #e5e5e5;
  cursor: pointer;
  padding:.5em;
  color: #222222;
}
.mb-item.active {
  background: #E9EFFF !important;
  color: #025FFF !important;
}
.x-tab-item { 
  background: #F2F2F2;
  color: #222222;
  display: inline-block;
  padding: 5px 18px;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 5px;
  font-family: Roboto;
}
.x-tab-item.active {
  background: #E9EFFF !important;
  color: #025FFF !important;
}
@media screen and (min-width: 1000px) {

}
@media screen and (min-width: 1200px) {
  .x-tab-item {
    padding: 5px 12px;
    margin-right: 5px;
    font-size: 12px;
  }
}
@media screen and (min-width: 1400px) {
  .x-tab-item {
    padding: 5px 12px;
    margin-right: 5px;
    font-size: 14px;
  }
}
@media screen and (min-width: 1500px) {
  .x-tab-item {
    padding: 5px 18px;
    margin-right: 8px;
    font-size: 14px;
  }
}
</style>

